<?php
/**
 * Created by JetBrains PhpStorm.
 * User: GMC02
 * Date: 10/15/13
 * Time: 2:41 PM
 * To change this template use File | Settings | File Templates.
 */
class IsbnValidator extends CValidator {
    const ISBN10 = '10';
    const ISBN13 = '13';
    public $type = self::ISBN10;
    private $isbn_10_pattern = '/^[0-9]{9}[0-9X]{1}$/';
    private $isbn_13_pattern = '/^[0-9]{13}$/';

    protected function validateAttribute($object,$attribute){
        $pattern = $this->type === self::ISBN10 ? $this->isbn_10_pattern : $this->isbn_13_pattern;
        $value = $object->$attribute;
        if(!preg_match($pattern, $value)) {
            $this->addError($object,$attribute,'Your ISBN is invalid!');
        }
    }
}